package com.qingke.studentinfo.Dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.qingke.studentinfo.Utils.ConstantUtils;

public abstract class BaseDao implements ConstantUtils {

	protected Connection getConnection() {
		try {
			Class.forName(JDBC_DRIVER);
			return DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	protected void closeAll(Connection conn, Statement stmt, ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
			if (stmt != null)
				stmt.close();
			if (conn != null)
				conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected int update(String sql, Object... obj) {
		int result = 0;
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			conn = getConnection();
			//不自动提交事务
			conn.setAutoCommit(false);
			pstmt = conn.prepareStatement(sql);
			for(int i = 0; i < obj.length; i++) {
				pstmt.setObject(i+1, obj[i]);
			}
			result = pstmt.executeUpdate();
			conn.commit();
		}catch(Exception e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			closeAll(conn, pstmt, null);
		}
		
		return result;
	}
}
